//引用Vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import {
	BindUser,
	GetUnreadMsg
} from '@/request/Api/chat.js'
const store = new Vuex.Store({
	state: {
		userId: 0,
		// 会话列表
		ChatList: [],
		Loginstatus: false,
		//socket链接状态
		IsOpen: false,
		//task对象
		SocketTask: false,
		//是否在线
		IsOnline: false,
		// 聊天对象
		ToUser: {
			userId: 0,
			nikename: '',
			userPic: ''
		}
	},
	//相当与计算属性
	getters: {
		// 获取角标数量
		getBadgeNum(state) {
			const userinfo = uni.getStorageSync('userInfo')
			const list = uni.getStorageSync('chatList_' + userinfo.id)
			const chatlist = list ? JSON.parse(list) : []
			let num = 0
			chatlist.forEach(v => {
				num += v.noread
			})
			return num
		}
	},
	//获取userId
	//mutations是修改store数据入口
	mutations: {
		//关闭Socket
		CloseSocket(state) {
			if (state.IsOpen) {
				state.SocketTask.close()
			}
		},
		updateUserId(state, msg) {
			state.userId = msg;
			state.Loginstatus = true;
		},
		// 创建聊天对象
		createTouser(state, ToUser) {
			console.log(ToUser)
			state.ToUser = ToUser
		},
		//清空聊天对象
		clearToUser(state) {
			state.ToUser = {
				userId: 0,
				nikename: '',
				userPic: ''
			}
		}
	},
	//异步函数
	actions: {
		initUser({
			state,
			dispatch
		}) {
			console.log('初始化用户')
			//判断是否登录
			const userInfo = uni.getStorageSync('userInfo')
			console.log(userInfo)
			if (userInfo) {
				state.Loginstatus = true
				state.userId = userInfo.id
				// 连接Socket
				if (!state.IsOpen) {
					dispatch('OpenSocket')
				}
			}
		},
		// 第一个参数是内容，第二个是执行函数
		OpenSocket({
			state,
			dispatch
		}) {
			//防止重复连接
			if (state.IsOpen) return
			//获取连接后的task对象
			state.SocketTask = uni.connectSocket({
				url: 'ws://192.168.133.79:8081/chat',
				complete: () => {

				}
			})
			//监听连接成功
			state.SocketTask.onOpen(() => {
				console.log('连接成功')
				state.IsOpen = true;
			})
			//监听连接失败
			state.SocketTask.onError(() => {
				console.log('连接失败')
				state.IsOpen = false;
				state.SocketTask = false;
				state.IsOnline = false;
			})
			//监听连接关闭
			state.SocketTask.onClose(() => {
				console.log('连接关闭')
				state.IsOpen = false;
				state.SocketTask = false;
				state.IsOnline = false;
				//清空回话列表
				//更新未读数提示
			})
			//监听接收到的消息
			state.SocketTask.onMessage((msg) => {
				console.log('收到消息')
				console.log(msg)
				const data = JSON.parse(msg.data)
				console.log(data.data)
				if (data.type === 'bind') {
					return dispatch('userBind', data.data)
				}
				//这里我只能传文字消息
				//处理接受消息
				dispatch('handelMessage', data)
			})
		},
		//绑定用户
		userBind({
			state,
			dispatch
		}, clientId) {
			BindUser({
				type: 'bind',
				data: clientId
			}).then((res) => {
				if (res.code === 1) {
					console.log('绑定成功')
					state.IsOnline = true;
					// 获取未上线时的信息
					dispatch("getUnreadMessage")
					// 初始化回话列表
					dispatch("initChatList")
				}

			}).catch((res) => {
				//错误
			})
		},
		async processMessages({dispatch},res) {
			for(let i = 0;i<res.data.length;i++)
			{
				await dispatch('handelMessage', res.data[i])
			}
		/* 	res.data.forEach(v=>{
				await dispatch('handelMessage', v)
			}) */
			/* for (const v of res.data) {
				try {
					await store.dispatch('handelMessage', v);
				} catch (error) {
					console.error(`处理消息 ${v} 时出现错误:`, error);
					// 可以根据需求决定是否继续处理下一条消息，这里选择继续处理
					continue;
				}
			} */
		},
		//未读消息
		getUnreadMessage({
			state,
			dispatch,
			commit
		}) {
			GetUnreadMsg().then((res) => {
				console.log('获取未上线时的消息', res.data)
				return dispatch('processMessages', res);
			})
		},
		async handelMessage({
			state,
			dispatch
		}, data) {
			console.log('处理消息', data)
			//全局通知接口

			//存储消息到chatdetailList中
			await dispatch('updateChatDetailList', {
				data: data,
				send: false
			})
			//更新会话列表
			await dispatch('updateChatList', data)
			uni.$emit('UserChat', data)
		},
		async updateChatDetailList({
			state,
			dispatch,
			commit
		}, obj) {
			console.log('存储消息到chatdetailList中')
			let data = obj.data
			let to_id = obj.send ? state.ToUser.userId : data.fromId
			//获取与某个用户的聊天记录
			let list = await dispatch('getChatdetailList', to_id)
			console.log(list)
			//保存到本地
			list.push(await dispatch("formatChatdetailObject", obj))
			const userId = uni.getStorageSync('userInfo').id + ''
			//保存到本地
			uni.setStorageSync('chatdetailList_' + userId + '_' + to_id, JSON.stringify(list))
		},
		getChatdetailList({
			state,
			dispatch,
			commit
		}, toId) {
			let myId = uni.getStorageSync('userInfo').id + ''
			let key = 'chatdetailList_' + myId + '_' + toId
			let list = uni.getStorageSync(key)
			return list ? JSON.parse(list) : []
		},
		async initChatList({
			state,
			dispatch,
			commit
		}) {
			//获取会话列表
			const userinfo = uni.getStorageSync('userInfo')
			let list = uni.getStorageSync('chatList_' + userinfo.id)
			let chatlist = list ? JSON.parse(list) : []
			state.ChatList = chatlist
			//更新未读数
			dispatch("updateTabarBadge")
		},
		formatChatdetailObject({
			state,
			dispatch,
			commit
		}, e) {
			let data = e.data
			const userId = uni.getStorageSync('userInfo').id
			return {
				userId: e.send ? userId : data.fromId,
				nikename: data.fromName,
				userPic: data.fromPic,
				create_time: data.time,
				data: data.data,
				type: data.type,
			}
		},
		async updateChatList({
			state,
			dispatch,
			commit
		}, data) {
			console.log('更新回话列表', data)
			//是否是本人发送
			const userinfo = uni.getStorageSync('userInfo')
			let isMysend = data.fromId === userinfo.id
			console.log(isMysend)
			// 获取所有回话列表
			let list = uni.getStorageSync('chatList_' + userinfo.id)
			let chatlist = list ? JSON.parse(list) : []
			//找到这个回话是否存在
			let index = chatlist.findIndex((item) => {
				//这里是本人先发的话存的就是本人id，他人先发就是存的他人id
				return parseInt(item.userId) === parseInt(data.fromId) || parseInt(item.userId) === parseInt(data.toId)
			})

			//不存在
			if (index === -1) {
				let obj = await dispatch('formatChatlistObject', {
					data: data,
					send: isMysend
				})
				//更新未读数
				if (!isMysend && state.ToUser.userId !== data.fromId) {
					obj.noread++
				}
				chatlist.unshift(obj)
			}
			//存在
			else {
				let item = chatlist[index]
				//更新时间
				item.time = data.time
				//更新内容
				item.data = data.data
				item.type = data.type
				//更新未读数
				if (!isMysend && state.ToUser.userId !== data.fromId) {
					item.noread++
				}
				//更新列表
				chatlist.splice(index, 1)
				chatlist.unshift(item)
			}
			//保存在本地
			uni.setStorageSync('chatList_' + userinfo.id, JSON.stringify(chatlist))
			//更新未读数角标
			if (!isMysend && state.ToUser.userId !== data.fromId) {
				console.log('更新未读数角标')
				await dispatch('updateTabarBadge')
			}
		},
		updateTabarBadge({
			state,
			getters
		}) {
			const userinfo = uni.getStorageSync('userInfo')
			const list = uni.getStorageSync('chatList_' + userinfo.id)
			const chatlist = list ? JSON.parse(list) : []
			let BadgeNum = 0
			chatlist.forEach(v => {
				BadgeNum += v.noread
			})
			console.log(BadgeNum)
			//更新未读数角标
			if (BadgeNum) {
				uni.setTabBarBadge({
					index: 1,
					text: BadgeNum > 99 ? '99+' : BadgeNum.toString()
				})
			} else {
				uni.removeTabBarBadge({
					index: 1
				})
			}
		},
		formatChatlistObject({
			state
		}, e) {
			console.log(state.ToUser)
			return {
				userId: e.send ? state.ToUser.userId : e.data.fromId,
				nikename: e.send ? state.ToUser.nikename : e.data.fromName,
				userPic: e.send ? state.ToUser.userPic : e.data.fromPic,
				time: e.data.time, //发送时间
				data: e.data.data,
				noread: 0 //未读数
			}
		},
		async sendMessage({
			state,
			dispatch,
			commit
		}, data) {
			//发送消息
			/* 
			{
				data:data,
				type:type
			} 
			 */
			let senddata = await dispatch('FormatSedMessage', data)
			//更新聊天记录
			dispatch('updateChatDetailList', {
				data: senddata,
				send: true
			})
			console.log(111)
			//更新回话列表
			dispatch('updateChatList', senddata)

			return senddata
		},
		FormatSedMessage({
			state
		}, data) {
			const userInfo = uni.getStorageSync('userInfo')
			console.log(userInfo)
			return {
				toId: state.ToUser.userId,
				fromId: userInfo.id,
				fromName: userInfo.nikeName,
				fromPic: userInfo.userpic,
				time: new Date().getTime(),
				data: data.data,
				type: data.type
			}
		},
		// 读取当前会话（去除未读数
		readChatMessage({
			state,
			dispatch,
			commit
		}, item) {
			/* {userId: data.fromId,
						nikename: data.fromName,
						userPic: data.userPic,
						time: data.time, //发送时间
						data: data.data,
						unreadNum: 0,
						noread: 0 //未读数} */
			console.log("读取当前会话", item)
			if (item.noread === 0) {
				return
			}

			const userinfo = uni.getStorageSync('userInfo')
			const list = uni.getStorageSync('chatList_' + userinfo.id)
			let ChatList = list ? JSON.parse(list) : []
			ChatList.forEach((v) => {
				if (v.userId === item.userId) {
					v.noread = 0
				}
			})
			if (userinfo) {
				//保存在本地
				uni.setStorageSync('chatList_' + userinfo.id, JSON.stringify(ChatList))
				dispatch('updateTabarBadge')
			}

		}


	}

})

export default store